<?php
/**
 * Created by PhpStorm.
 * User: aiChenK
 * Date: 2018-03-12
 * Time: 11:15
 */

namespace Admin\Frontend\Controllers;

use Admin\Models\sys\XhsysEnum;
use Admin\Models\user\XhsysUser;
use Admin\Models\user\XhsysUserpower;
use Helpers\Tool;
use Helpers\User;
use Helpers\Assets;
use Helpers\Template;
use Admin\Models\coop\XhCoopInfo;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\sys\XhsysUserextrapower;
use Modules\School;
use Services\ConfigManage;

class PowerController extends ControllerBase
{

    private $type = [
        'school'    => '学校',
        'dep'       => '部门',
        'userGroup' => '用户组',
        'coop'      => '供应商',
        'product'      => '产品',
        'resManage' => '资源管理',
        'config'    => '配置'
    ];

    private function getExtraPower($goal, $goalId, $type, $target, $manage = 0)
    {
        return XhsysUserextrapower::findFirst([
            'conditions' => 'bDelete = 0 AND iGoal = :goal: AND iGoalId = :goalId: 
                AND sType = :type: AND sTarget = :target: AND bManage = :manage:',
            'bind' => ['goal' => $goal, 'goalId' => $goalId, 'type' => $type, 'target' => $target, 'manage' => $manage]
        ]);
    }

    private function getExistExtraPower($goal, $goalId, $type, $target, $manage = 0)
    {
        $power = $this->getExtraPower($goal, $goalId, $type, $target, $manage);
        if (!$power) {
            $power = new XhsysUserextrapower([
                'iGoal'   => $goal,
                'iGoalId' => $goalId,
                'sType'   => $type,
                'sTarget' => $target,
                'bManage' => $manage,
                'mContent'=> []
            ]);
        }
        return $power;
    }

    /**
     * 公共扩展权限页面
     *
     * @return \Phalcon\Mvc\View|string

     * create by ck 20180821
     *  modify by zsc 20180920    增加资源管理扩展权限
     */
    public function extraAction()
    {
        $goal   = $this->request->getQuery('goal', 'int');
        $goalId = $this->request->getQuery('goalId', 'int');
        $type   = $this->request->getQuery('type', 'string');
        $target = $this->request->getQuery('target', 'string');
        $extend = $this->request->getQuery('extend', 'string');

        if (!$goal || !$goalId || !$type || !$target) {
            return $this->sendViewError('缺少参数');
        }
        $this->view->pick('power/extra');
        $types  = explode('|', $type);
        $params = ['goal' => $goal, 'goalId' => $goalId, 'target' => $target];
        $data   = [];
        foreach ($types as $type) {
            if (!array_key_exists($type, $this->type)) {
                return $this->sendViewError('类型不正确');
            }
            if ($type == 'resManage') { //此段张世川加，有疑问请联系张世川
                $extend = explode(',', $extend);
                if (in_array('subject', $extend)) {
                    $data[] = [
                        'name'  => $this->type[$type] . '-学科管理',
                        'url'   => $this->url->get(
                            sprintf('/power/%sExtra', $type),
                            array_merge($params, ['type' => $type, 'manage' => 0,'extend'=> 'Subject' ])
                        ),
                        'id'    => $type . '_' . $target . '_subject'
                    ];
                }
                if (in_array('grade', $extend)) {
                    $data[] = [
                        'name'  => $this->type[$type] . '-年级管理',
                        'url'   => $this->url->get(
                            sprintf('/power/%sExtra', $type),
                            array_merge($params, ['type' => $type, 'manage' => 0,'extend'=> 'Grade'])
                        ),
                        'id'    => $type . '_' . $target . '_grade'
                    ];
                }
            } else {
                $data[] = [
                    'name'  => $this->type[$type] . '-管理',
                    'url'   => $this->url->get(
                        sprintf('/power/%sExtra', $type),
                        array_merge($params, ['type' => $type, 'manage' => 1])
                    ),
                    'id'    => $type . '_' . $target . '_1'
                ];
                $data[] = [
                    'name'  => $this->type[$type] . '-查看',
                    'url'   => $this->url->get(
                        sprintf('/power/%sExtra', $type),
                        array_merge($params, ['type' => $type, 'manage' => 0])
                    ),
                    'id'    => $type . '_' . $target . '_0'
                ];
            }

        }
        return $this->view->setVar('data', $data);
    }


    /**
     * 获取部门扩展权限
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180329
     * modify by ck 20180503    字段更改
     * modify by ck 20180821    增加是否管理字段
     */
    public function getExtraPowerAction()
    {
        $goal   = $this->request->getPost('goal', 'int');
        $goalId = $this->request->getPost('goalId', 'int');
        $type   = $this->request->getPost('type', 'string');
        $target = $this->request->getPost('target', 'string');
        $manage = $this->request->getPost('manage', 'int', 0);
        if (!$goal || !$goalId || !$type || !$target) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        try {
            $power = $this->getExtraPower($goal, $goalId, $type, $target, $manage);
//            $power = XhsysUserextrapower::findFirst([
//                'conditions' => 'bDelete = 0 AND iGoal = :goal: AND iGoalId = :goalId:
//                      AND sType = :type: AND sTarget = :target:',
//                'bind'       => ['goal' => $goal, 'goalId' => $goalId, 'type' => $type, 'target' => $target]
//            ]);
            if (!$power) {
                return $this->sendJsonResponse(['powerIds' => [], 'all' => false]);
            }
            return $this->sendJsonResponse(['powerIds' => $power->mContent, 'all' => !!$power->bAll]);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '权限获取失败', $e->getMessage());
        }
    }

    /**
     * 保存部门扩展权限
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180329
     * modify by ck 20180503    字段更改
     * modify by ck 20180606    新增operate操作，可新增/删除
     * modify by ck 20180821    增加是否管理字段
     */
    public function saveExtraPowerAction()
    {
        $goal   = $this->request->getPost('goal', 'int');
        $goalId = $this->request->getPost('goalId', 'int');
        $type   = $this->request->getPost('type', 'string');
        $target = $this->request->getPost('target', 'string');
        $manage = $this->request->getPost('manage', 'int', 0);
        $ids    = $this->request->getPost('ids', 'int');
        $operate= $this->request->getPost('operate', 'string');
        if (!$goal || !$goalId || !$type) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        try {
//            $power = XhsysUserextrapower::findFirst([
//                'conditions' => 'bDelete = 0 AND iGoal = :goal: AND iGoalId = :goalId:
//                      AND sType = :type: AND sTarget = :target:',
//                'bind'       => ['goal' => $goal, 'goalId' => $goalId, 'type' => $type, 'target' => $target]
//            ]);
//            if (!$power) {
//                $power = new XhsysUserextrapower([
//                    'iGoal'   => $goal,
//                    'iGoalId' => $goalId,
//                    'sType'   => $type,
//                    'sTarget' => $target,
//                    'mContent'=> []
//                ]);
//            }
            $power = $this->getExistExtraPower($goal, $goalId, $type, $target, $manage);
            switch ($operate) {
                case 'add':
                    $ids = array_values(array_unique(array_merge($power->mContent, $ids)));
                    break;
                case 'del':
                    $ids = array_values(array_diff($power->mContent, $ids));
                    break;
            }
            $power->mContent = $ids;
            if (!$power->save()) {
                throw new \Exception($power->getError());
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '保存失败', $e->getMessage());
        }
    }

    /**
     * 设置所有权限
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180606
     * modify by ck 20180821    增加是否管理字段
     */
    public function saveExtraAllPowerAction()
    {
        $goal   = $this->request->getPost('goal', 'int');
        $goalId = $this->request->getPost('goalId', 'int');
        $type   = $this->request->getPost('type', 'string');
        $target = $this->request->getPost('target', 'string');
        $all    = $this->request->getPost('all', 'string');
        $manage = $this->request->getPost('manage', 'int', 0);
        if (!$goal || !$goalId || !$type) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        try {
//            $power = XhsysUserextrapower::findFirst([
//                'conditions' => 'bDelete = 0 AND iGoal = :goal: AND iGoalId = :goalId:
//                      AND sType = :type: AND sTarget = :target:',
//                'bind'       => ['goal' => $goal, 'goalId' => $goalId, 'type' => $type, 'target' => $target]
//            ]);
//            if (!$power) {
//                $power = new XhsysUserextrapower([
//                    'iGoal'   => $goal,
//                    'iGoalId' => $goalId,
//                    'sType'   => $type,
//                    'sTarget' => $target,
//                    'mContent'=> []
//                ]);
//            }
            $power = $this->getExistExtraPower($goal, $goalId, $type, $target, $manage);
            $power->bAll = $all;
            if (!$power->save()) {
                throw new \Exception($power->getError());
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '保存失败', $e->getMessage());
        }
    }

    /**
     * 部门权限设置
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180329
     */
    public function depExtraAction()
    {
        $this->view->setTemplateBefore('listForm');
        $this->view->pick('power/depExtra');
        Assets::easyUI('js/power/depExtra.js');
        $goal   = $this->request->getQuery('goal', 'int');
        $goalId = $this->request->getQuery('goalId', 'int');
        if (!$goal || !$goalId) {
            return $this->sendViewError('缺少参数');
        }
        return $this->view->setVars([
            'List'      => Template::createList('list', 'Power_Dep'),
            'isAdmin'   => User::isAdmin()
        ]);
    }

    /**
     * 产品权限设置
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by zqk 20181016
     */
    public function productExtraAction()
    {
        $this->view->setTemplateBefore('listForm');
        Assets::easyUI('js/power/productExtra.js');
        $goal   = $this->request->getQuery('goal', 'int');
        $goalId = $this->request->getQuery('goalId', 'int');

        if (!$goal || !$goalId) {
            return $this->sendViewError('缺少参数');
        }
        $searchArr[] = ['type' => 'text', 'id' => 'productName', 'label' => ' 产品名称: ','style' => 'margin: 0px;
                padding-top: 0px;padding-bottom: 0px;height: 20px;line-height: 20px;width: 133px;border: 1px solid #ccc; border-radius: 0;'];
        $searchArr[] = [
            'type' => 'button',
            'id' => 'bt_search',
            'text' => '查找',
            'icon' => 'fa-search',
            'style' => 'margin-left:10px;cursor:pointer'
        ];
        return $this->view->setVars([
            'List'      => Template::createList('list', 'Power_Product',[
                'searchToolbar' => Template::createSearchToolBar($searchArr),
            ]),
            'isAdmin'   => User::isAdmin()
        ]);
    }

    /**
     * 用户组扩展权限设置
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180502
     */
//    public function userGroupExtraAction()
//    {
//        $this->view->setTemplateBefore('listForm');
//        Assets::easyUI('js/power/userGroupExtra.js');
//        $goal   = $this->request->getQuery('goal', 'int');
//        $goalId = $this->request->getQuery('goalId', 'int');
//        if (!$goal || !$goalId) {
//            return $this->sendViewError('缺少参数');
//        }
//        return $this->view->setVars([
//            'List'      => Template::createList('list', 'Group_List', [
//                'tableAttr' => [
//                    'singleSelect'  => false,
//                    'pagination'    => false
//                ]
//            ]),
//            'isAdmin'   => User::isAdmin()
//        ]);
//    }

    /**
     * 学校扩展权限总页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180518
     * modify by ck 20180821    结构更改
     */
//    public function schoolTotalExtraAction()
//    {
//        $this->view->pick('power/schoolTotalExtra');
//        Assets::easyUI('js/power/schoolTotalExtra.js');
//        $goal   = $this->request->getQuery('goal', 'int');
//        $goalId = $this->request->getQuery('goalId', 'int');
//        if (!$goal || !$goalId) {
//            return $this->sendViewError('缺少参数');
//        }
//        $params = ['goal' => $goal, 'goalId' => $goalId];
//        return $this->view->setVars([
//            'viewUrl'   => $this->url->get('/power/schoolExtra', array_merge($params, ['target' => 'main', 'manage' => 0])),
//            'manageUrl' => $this->url->get('/power/schoolExtra', array_merge($params, ['target' => 'main', 'manage' => 1]))
//        ]);
//    }


    /**
     * 学校扩展权限页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180518
     */
    public function schoolExtraAction()
    {
        $this->view->pick('power/schoolExtra');
        Assets::easyUI('js/power/schoolExtra.js');
        $goal   = $this->request->getQuery('goal', 'int');
        $goalId = $this->request->getQuery('goalId', 'int');
        if (!$goal || !$goalId) {
            return $this->sendViewError('缺少参数');
        }
        $outSearchArr = [];
        $outSearchArr[] = ['type'=>'text', 'id'=>'list_out_vague', 'label'=>'搜索： '];
        $outSearchArr[] = ['type'=>'button','id'=>'bt_list_out_search', 'text'=>'确定', 'icon'=>'fa-search', 'style'=>'margin-left:10px'];
        return $this->view->setVars([
            'List'      => Template::createList('in_list', 'XHSchool_Info', [
                'title'         => '已添加列表',
                'tableAttr'     => ['pagination' => 'false'],
                'field'         => ['iSchoolId', 'sSchoolName']
            ]),
            'OutList'   => Template::createList('out_list', 'XHSchool_Info', [
                'title'         => '未添加列表',
                'searchToolbar' => Template::createSearchToolBar($outSearchArr)
            ]),
            'isAdmin'   => User::isAdmin()
        ]);
    }

    /**
     * 获取学校权限列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180605
     * modify by ck 20180821    更改权限获取方法
     */
    public function getSchoolPowerAction()
    {
        $goal   = $this->request->getPost('goal', 'int');
        $goalId = $this->request->getPost('goalId', 'int');
        $type   = $this->request->getPost('type', 'string');
        $target = $this->request->getPost('target', 'string');
        $manage = $this->request->getPost('manage', 'int', 0);
        if (!$goal || !$goalId || !$type || !$target) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        try {
            $power = $this->getExtraPower($goal, $goalId, $type, $target, $manage);
            if (!$power) {
                return $this->sendJsonResponse(['total' => 0, 'rows' => [], 'all' => false]);
            }
            $schoolIds = $power->mContent;
            $schools   = School::getSchools(true);
            $rows      = array_map(function ($schoolId) use ($schools) {
                return ['iSchoolId' => $schoolId, 'sSchoolName' => $schools[$schoolId]];
            }, $schoolIds);
            return $this->sendJsonResponse(['total' => count($rows), 'rows' => $rows, 'all' => $power->bAll]);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '权限获取失败', $e->getMessage());
        }
    }

    /**
     * 配置扩展权限页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180518
     */
    public function configExtraAction()
    {
        $this->view->pick('power/configExtra');
        Assets::easyUI('js/power/configExtra.js');
        $goal   = $this->request->getQuery('goal', 'int');
        $goalId = $this->request->getQuery('goalId', 'int');
        if (!$goal || !$goalId) {
            return $this->sendViewError('缺少参数');
        }
        $outSearchArr = [];
        $outSearchArr[] = ['type'=>'text', 'id'=>'list_out_vague', 'label'=>'搜索： '];
        $outSearchArr[] = ['type'=>'button','id'=>'bt_list_out_search', 'text'=>'确定',
            'icon'=>'fa-search', 'style'=>'margin-left:10px'];
        return $this->view->setVars([
            'List'      => Template::createList('in_list', 'XHSys_Config', [
                'title'         => '已添加列表',
                'tableAttr'     => ['pagination' => 'false'],
                'field'         => ['iSCId', 'sConfigExplain']
            ]),
            'OutList'   => Template::createList('out_list', 'XHSys_Config', [
                'title'         => '未添加列表',
                'searchToolbar' => Template::createSearchToolBar($outSearchArr)
            ]),
            'isAdmin'   => User::isAdmin()
        ]);
    }

    /**
     * 获取配置权限列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180605
     * modify by ck 20180821    更改权限获取方法
     */
    public function getConfigPowerAction()
    {
        $goal   = $this->request->getPost('goal', 'int');
        $goalId = $this->request->getPost('goalId', 'int');
        $type   = $this->request->getPost('type', 'string');
        $target = $this->request->getPost('target', 'string');
        $manage = $this->request->getPost('manage', 'int', 0);
        if (!$goal || !$goalId || !$type || !$target) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        try {
            $power = $this->getExtraPower($goal, $goalId, $type, $target, $manage);
            if (!$power) {
                return $this->sendJsonResponse(['total' => 0, 'rows' => [], 'all' => false]);
            }
            $configs = $power->mContent;
            $schools   = ConfigManage::getConfig($target);
            $rows      = array_map(function ($config) use ($schools) {
                return ['iSCId' => $config, 'sConfigExplain' => $schools[$config]];
            }, $configs);
            return $this->sendJsonResponse(['total' => count($rows), 'rows' => $rows, 'all' => $power->bAll]);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '权限获取失败', $e->getMessage());
        }
    }

    /**
     * 合作商扩展权限
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180820
     */
    public function coopExtraAction()
    {
        $this->view->pick('power/coopExtra');
        Assets::easyUI('js/power/coopExtra.js');
        $goal   = $this->request->getQuery('goal', 'int');
        $goalId = $this->request->getQuery('goalId', 'int');
        if (!$goal || !$goalId) {
            return $this->sendViewError('缺少参数');
        }
        return $this->view->setVars([
            'List'      => Template::createList('in_list', 'Power_Coop', [
                'title'         => '已添加列表',
                'tableAttr'     => ['pagination' => 'false'],
            ]),
            'OutList'   => Template::createList('out_list', 'Power_Coop', [
                'title'         => '未添加列表',
            ]),
            'isAdmin'   => User::isAdmin()
        ]);
    }

    /**
     * 获取已有合作商扩展权限
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180820
     */
    public function getCoopPowerAction()
    {
        $goal   = $this->request->getPost('goal', 'int');
        $goalId = $this->request->getPost('goalId', 'int');
        $type   = $this->request->getPost('type', 'string');
        $target = $this->request->getPost('target', 'string');
        $manage = $this->request->getPost('manage', 'int', 1);
        if (!$goal || !$goalId || !$type || !$target) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        try {
            $power = $this->getExtraPower($goal, $goalId, $type, $target, $manage);
            if (!$power) {
                return $this->sendJsonResponse(['total' => 0, 'rows' => [], 'all' => false]);
            }
            $powerIds = $power->mContent;
            if (!$powerIds) {
                return $this->sendJsonResponse(['total' => 0, 'rows' => [], 'all' => $power->bAll]);
            }
            $rows = XhCoopInfo::find([
                'columns' => 'iCIId,sName,sLegalName,sPhoneNum,sAddress',
                'conditions' => 'bDelete = 0 AND iCIId IN ({coopIds:array})',
                'bind' => ['coopIds' => $powerIds]
            ])->toArray();
            return $this->sendJsonResponse(['total' => count($rows), 'rows' => $rows, 'all' => $power->bAll]);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '权限获取失败', $e->getMessage());
        }
    }


    /**
     * 方法说明 :设置权限资源管理的科目分类
     * @return mixed
     * Created by zsc 20180920
     */
    public function resManageExtraAction()
    {
        $this->view->setTemplateBefore('listForm');
        $this->view->pick('power/resManageExtra');
        Assets::easyUI('js/power/resManageExtra.js');
        $goal   = $this->request->getQuery('goal', 'int');
        $goalId = $this->request->getQuery('goalId', 'int');
        if (!$goal || !$goalId) {
            return $this->sendViewError('缺少参数');
        }
        return $this->view->setVars([
            'List'      => Template::createList('list', 'Power_resManage'),
            'isAdmin'   => User::isAdmin()
        ]);
    }

    /**
     * 根据权限标识展示已存在该权限的用户及组
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20181030
     */
    public function existPowerUserAction()
    {
        $powerTag = $this->request->getQuery('powerTag', 'string');
        if (!$powerTag) {
            return $this->sendViewError('权限不可为空');
        }
        $this->view->pick('power/existPowerUser');
        try {
            //获取用户列表
            $users = $this->db->fetchAll("SELECT u.iUserId,u.sLogonName,u.sUserName,u.sSelfPhone 
              FROM `XHSys_UserPower` AS p 
              LEFT JOIN XHSys_User AS u ON p.iUPUserId = u.iUserId 
              WHERE p.bDelete = 0 AND u.bDelete = 0 AND bHistory = 0 AND find_in_set('{$powerTag}', p.mUPowerTag)");

            //获取组列表
            $groups = $this->db->fetchAll("SELECT g.iGroupId,g.sName,g.iType
              FROM XHSys_GroupPower AS p
              LEFT JOIN XHSys_Group AS g ON p.iGroupId = g.iGroupId
              WHERE g.bDelete = 0 AND p.bDelete = 0 AND find_in_set('{$powerTag}', p.mPowerTag)");
            Tool::runEnum($groups, ['iType' => XhsysEnum::getEnumByNodeName('用户组')]);

            return $this->view->setVars([
                'users' => $users,
                'groups' => $groups
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }
}